package com.king.util;

import java.util.LinkedHashMap;
import java.util.Map;

import javafx.scene.Node;
import javafx.util.Callback;
import net.rgielen.fxweaver.core.FxControllerAndView;
import net.rgielen.fxweaver.core.FxWeaver;

/**
 * 继承FXWeaver，实现加载FXML并缓存之
 * 
 * @author king
 * @date 2025年7月8日-16:32:16
 */
public class LoadFXML extends FxWeaver {

	/**
	 * 仅支持缓存数量为5个，初始化为6，降低容器扩容为10
	 */
	private final static Map<Class<?>, FxControllerAndView<?, ?>> CACHE = new LinkedHashMap<Class<?>, FxControllerAndView<?, ?>>(
			6, 0.9f, false) {
		/**
		 * @author king
		 * @date 2025年7月8日-17:26:33
		 */
		private static final long serialVersionUID = 1L;
		@Override
		protected boolean removeEldestEntry(Map.Entry<Class<?>, FxControllerAndView<?, ?>> eldest) {
			return size() > 5;
		}
	};

	public LoadFXML(Callback<Class<?>, Object> beanFactory, Runnable closeCommand) {
		super(beanFactory, closeCommand);
	}

	@SuppressWarnings("unchecked")
	public <C, V extends Node> FxControllerAndView<C, V> loadAndCache(Class<C> controllerClass) {
		if (CACHE.containsKey(controllerClass)) {
			return (FxControllerAndView<C, V>) CACHE.get(controllerClass);
		} else {
			FxControllerAndView<C, V> o = load(controllerClass, null);
			CACHE.put(controllerClass, (FxControllerAndView<?, ?>) o);
			return o;
		}
	}

	/**
	 * 清除缓存
	 * 
	 * @param <C>
	 * @param controllerClass
	 * @author king
	 * @date 2025年7月8日-16:42:03
	 */
	public <C> void clearCache(Class<C> controllerClass) {
		CACHE.remove(controllerClass);
	}
}
